import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import defAva from '@/assets/images/profile.jpg'

export const useUserStore = defineStore(
  'user',
  {
    state: () => ({
      token: getToken(),
      // 登录用户信息
      userInfo: {},
      id: '',
      name: '',
      avatar: '',
      roles: [],
      permissions: []
    }),
    actions: {
      // 登录
      login(userInfo) {
        return new Promise((resolve, reject) => {
          login(userInfo).then(res => {
            console.log(res)
            setToken(res.data.accessToken)
            this.token = res.data.accessToken
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 获取用户信息
      getInfo() {
        return new Promise((resolve, reject) => {
          getInfo().then(res => {
            const userData = res.data;
            const avatar = (userData.avatar == "" || userData.avatar == null) ? defAva : import.meta.env.VITE_APP_BASE_API + userData.avatar;
            this.userInfo = userData;
            // 如果后端返回了角色信息，则使用后端返回的角色信息
            if (userData.roles && userData.roles.length > 0) {
              this.roles = userData.roles;
              this.permissions = userData.perms || [];
            } else {
              // 如果后端没有返回角色信息，则使用默认角色
              this.roles = ['ROLE_DEFAULT'];
            }
            this.id = userData.userId;
            this.name = userData.nickname || userData.username;
            this.avatar = avatar;
            resolve(res);
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 退出系统
      logOut() {
        return new Promise((resolve, reject) => {
          logout(this.token).then(() => {
            this.token = ''
            this.roles = []
            this.permissions = []
            removeToken()
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      }
    },
    // 进行持久化存储
    persist: {
      // 本地存储的名称
      key: 'userState',
      //保存的位置
      storage: window.localStorage, //localstorage
    },
  }
)
